/*
 * Copyright 2006-2008 Michele Mostarda ( michele.mostarda@gmail.com ).
 * All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.graphnav.swing;

import org.graphnav.model.GraphModel;

import java.awt.Point;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;

/**
 * Arranges a set of nodes in a grid.
 */
public class GridNodeArranger implements NodeArranger {

    protected static final int MARGIN = 20;

    public static class Options {

        private int cols;

        public Options(int c) {
            if(c <= 0) { throw new IllegalArgumentException(); }

            this.cols = c;
        }

        int getCols() {
            return cols;
        }
    }

    public void arrange(GraphModel gm, int detailLevel, Node centralNode, EffectProcessor fp, Object options) {
        if( ! ( options instanceof Options) ) {
            throw new IllegalArgumentException();
        }

        final int cols = ( (Options) options).getCols();

        double currX = MARGIN;
        double currY = MARGIN;
        int currCol = 0;
        double maxHeight = 0;
        Iterator<Node> nodes = gm.nodes();
        Node node = null;
        Rectangle2D r2d = null;
        while(nodes.hasNext()) {
            node = nodes.next();
            fp.addMovement(node, new Point((int) currX, (int) currY));
            r2d = node.getBounds2D(detailLevel);
            if (r2d.getHeight() > maxHeight ) { maxHeight = r2d.getHeight(); }
            currX += r2d.getWidth() + MARGIN;
            currCol++;
            if(currCol >= cols) {
                currCol = 0;
                currX = MARGIN;
                currY += maxHeight + MARGIN;
            }
        }
        fp.moveToOrigin();
        fp.go();
    }

}
